<!--
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-01-29 20:04:48
 * @Description  : 分享管理
-->
<template>
  <div class="bg-lightColor share-con p-3 rounded" v-if="editModel === 'view'">
    <n-grid x-gap="12" :cols="1" class="mb-2">
      <n-gi class="flex">
        <time-select @time-change="handleTimeChange"></time-select>
        <UserSelect
          class="!w-[300px] ml-2"
          :multiple="false"
          @change-value="handleUserIdChange"
        ></UserSelect>
        <n-select
          v-model:value="pageInfo.type"
          :options="shareTypes"
          size="small"
          class="ml-2 !w-[120px]"
          :render-label="renderSelect"
          @update:value="loadShares"
        />
        <n-button
          class="ml-4"
          size="small"
          @click="exportSorterAndFilterCsv"
          type="tertiary"
        >
          导出
        </n-button>
      </n-gi>
    </n-grid>
    <wp-data-table
      :pages="pageResultInfo.pages"
      :total="pageResultInfo.total"
      v-loading="loading"
      :data="data"
      :checked-row-keys="checkedRowKeys"
      :columns="columns"
      @page-change="handlePageChange"
      @select-change="handleSelectChange"
      ref="shareTableRef"
    >
    </wp-data-table>
  </div>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import { useMessage, NButton, useDialog } from 'naive-ui'
import { NSwitch } from 'naive-ui'
import type { DataTableColumn, DataTableColumns } from 'naive-ui'
import useUserStore from '@/stores/modules/user'
import { delShare, getShareByPage } from '@/api/share'
import type { ShareRowData } from '@/types/share'
import { formatTime } from '@/utils/index'
import {
  renderSelect,
  renderShareExport,
  renderUserAvator
} from '@/utils/commonBusiness'
import { load } from '@/utils/loading'
import { getStartAndEndTime } from '@/utils'
import DisableUserPic from '@/assets/images/default-avata-disable.jpg'
import SvgIcon from '@/components/SvgIcon/index.vue'
import WpDataTable from '@/components/WpDataTable/index.vue'
import TimeSelect from '@/views/Admin/Log/components/TimeSelect.vue'
import { PERMISSIONS } from '@/constants/permission'
import type { IndexObj } from '@/types/commom'

const message = useMessage()
const dialog = useDialog()
const userStore = useUserStore()
const router = useRouter()

const data = ref<ShareRowData[]>([])
const pageInfo = reactive({
  page: 1,
  pageSize: 50,
  type: 2,
  userId: '',
  startTime:
    getStartAndEndTime(0).startTime!.format('YYYY-MM-DD HH:mm:ss') || undefined,
  endTime:
    getStartAndEndTime(0).endTime!.format('YYYY-MM-DD HH:mm:ss') || undefined
})

const shareTypes = ref([
  {
    value: 2,
    label: '全部'
  },
  {
    value: 0,
    label: '外链分享'
  },
  {
    value: 1,
    label: '内部协作'
  }
])

const loading = ref(false)

const pageResultInfo = reactive({
  pages: 0,
  total: 0
})

const handleTimeChange = (time: IndexObj) => {
  pageInfo.startTime = time.startTime
  pageInfo.endTime = time.endTime
  loadShares()
}

const handleUserIdChange = (value: string | string[]) => {
  pageInfo.userId = value as string
  loadShares()
}

const createColumns = (): DataTableColumns<ShareRowData> => {
  const selectColumn: DataTableColumn<ShareRowData> = {
    type: 'selection',
    minWidth: 30,
    width: 30
  }
  const staticColumns: DataTableColumns<ShareRowData> = [
    {
      title: '分享者',
      key: 'userInfo',
      minWidth: 150,
      width: 150,
      render: (row) => {
        if (!row.User) {
          return renderUserAvator(DisableUserPic, '已删除')
        }
        const curUsername =
          userStore.userInfo?.id === row.User?.id
            ? '我自己'
            : row.User?.username
        return renderUserAvator(
          row.User?.avator as string,
          curUsername as string
        )
      }
    },
    {
      title: '分享标题',
      key: 'title',
      minWidth: 120,
      width: 120,
      ellipsis: {
        tooltip: true
      }
    },
    {
      title: '分享类型',
      key: 'type',
      minWidth: 150,
      width: 150,
      render(row) {
        return [
          (row.isLink &&
            h(
              NTag,
              {
                class: 'cursor-pointer',
                style: {
                  fontSize: '13px'
                },
                type: 'success',
                bordered: false,
                onClick: () => handleToOpenShare(0, row)
              },
              {
                default: () => '外链'
              }
            )) ||
            '',
          (row.isShareTo &&
            h(
              NTag,
              {
                class: 'ml-1 cursor-pointer',
                style: {
                  fontSize: '13px'
                },
                type: 'info',
                bordered: false,
                onClick: () => handleToOpenShare(1, row)
              },
              {
                default: () => '内部分享'
              }
            )) ||
            ''
        ]
      }
    },
    {
      title: '详情',
      key: 'desc',
      minWidth: 120,
      width: 120
    },
    {
      title: '浏览数',
      key: 'numView',
      minWidth: 60,
      width: 60
    },
    {
      title: '下载数',
      key: 'numDownload',
      minWidth: 60,
      width: 60
    },
    {
      title: '分享时间',
      key: 'updateTime',
      minWidth: 150,
      width: 150,
      render(row) {
        return formatTime(row.createTime)
      }
    }
  ]

  const actionColumn: DataTableColumn<ShareRowData> = {
    title: '操作',
    minWidth: 120,
    width: 120,
    key: 'actions',
    render(row) {
      return h('div', [
        h(
          NButton,
          {
            text: true,
            type: 'primary',
            size: 'small',
            class: 'text-[13px]',
            onClick: () => handleToDel(row)
          },
          { default: () => '取消分享' }
        )
      ])
    }
  }

  if (
    userStore.permissions?.some((item) => {
      return item === PERMISSIONS.STORAGE_EDIT
    })
  ) {
    staticColumns.unshift(selectColumn)
    staticColumns.push(actionColumn)
  }
  return staticColumns
}

const checkedRowKeys = ref<string[]>([])

const columns = createColumns()

// 获取分享列表
const loadShares = () => {
  loading.value = true
  getShareByPage({
    ...pageInfo,
    type: pageInfo.type === 2 ? undefined : pageInfo.type,
    userId: pageInfo.userId === '' ? undefined : pageInfo.userId
  })
    .then((res) => {
      res.data.items.forEach((item) => {
        renderShareExport(item)
      })
      data.value = res.data.items
      pageResultInfo.pages = res.data.pages
      pageResultInfo.total = res.data.total
    })
    .catch(console.error)
    .finally(() => {
      loading.value = false
    })
}

onMounted(() => {
  loadShares()
})

const handlePageChange = (page?: number, pageSize?: number) => {
  page && (pageInfo.page = page)
  pageSize && (pageInfo.pageSize = pageSize)
}

const handleSelectChange = (rows: string[]) => {
  checkedRowKeys.value = rows.map((item) => item)
}

// 去添加分享
const handleToAdd = () => {
  editModel.value = 'create'
}

// 去编辑分享
const handleToUpdate = (row: ShareRowData) => {
  editModel.value = 'update'
}

// 打开共享页面
const handleToOpenShare = (type: number, row: ShareRowData) => {
  console.log('111')

  if (type === 0) {
    const route = router.resolve({
      name: 'linkShare',
      query: {
        shareId: row.id
      }
    })
    // 打开新tab页
    window.open(route.href, '_blank')
  } else if (type === 1) {
    // 打开协作对象
  }
}

// 去删除分享
const handleToDel = (row: ShareRowData) => {
  dialog.warning({
    title: '提示',
    content: '你确定要删除这些分享吗？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      load.show()
      delShare([row.id])
        .then(() => {
          message.success('操作成功')
          afterOpt()
        })
        .catch(console.error)
        .finally(() => {
          load.hide()
        })
    },
    onNegativeClick: () => {}
  })
}

const afterOpt = () => {
  loadShares()
}

// 去导出分享
const shareTableRef = ref()
const exportSorterAndFilterCsv = () =>
  shareTableRef.value!.tableRef!.downloadCsv({
    fileName: 'shares-' + dayjs().format('YYYY-MM-DD HH:mm:ss'),
    keepOriginalData: true
  })

// ================================= 分享新增和更新逻辑===============================================
const editModel = ref<'create' | 'update' | 'view'>('view')
</script>

<style scoped lang="scss">
.share-con {
  font-size: 13px;

  :deep(.n-data-table-tbody .n-data-table-tr:hover .n-data-table-td) {
    background-color: #e5f3ff;

    .move {
      opacity: 0.85;
    }
  }

  :deep(.my-handle) {
    height: 28px;
    line-height: 28px;
    // height: calc(100% + 16px);
    position: relative;
    .move {
      transition: all 0.3s var(--n-bezier);
      opacity: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #d1ecfa;
      color: $primaryColor;
      position: absolute !important;
      left: -8px;
      top: -8px;
      bottom: -8px;
      width: 40px;
      // right: 0;
      cursor: move;
    }
  }
}
</style>
